package com.jiaquyun.jcyx.main.mine

import android.graphics.Typeface
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.CartAction
import com.jiaquyun.jcyx.entity.CollectGoods
import com.jiaquyun.jcyx.jetpack.mode.UserViewModel
import com.module.lemlin.custom.SpacingItemDecoration
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeActivity
import kotlinx.android.synthetic.main.activity_mine_collect.*

class MineCollectActivity : OwnerViewModeActivity<UserViewModel>() {

    companion object {
        fun open() {
            ActivityUtils.startActivity(MineCollectActivity::class.java)
        }
    }

    private val mCollectGoodsAdapter = CollectGoodsAdapter()

    override fun viewModel(): UserViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_mine_collect

    override fun stateBar(): StatusBar {
        return StatusBar(isLightMode = true, color = R.color.white, view = flMineCollectBar)
    }

    override fun initView() {

        ivAppBack.setOnClickListener { finish() }

        rvMineCollectBody.apply {
            val decoration = SpacingItemDecoration(
                vGap = ConvertUtils.dp2px(10f),
                hGap = ConvertUtils.dp2px(10f)
            )
            addItemDecoration(decoration)
            itemAnimator?.changeDuration = 0
        }.adapter = mCollectGoodsAdapter

        mCollectGoodsAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData: CollectGoods = mCollectGoodsAdapter.getItem(position)
            if (view.id == R.id.ivGoodsPlus) {
                val num: Int = itemData.cart_num + 1
                if (itemData.cart_id == 0 || itemData.cart_num == 0) {
                    viewModel.cartAdd1(itemData.goods_id, num)
                } else {
                    viewModel.cartChangeNum1(itemData.goods_id, itemData.cart_id, num)
                }
            }
            if (view.id == R.id.ivGoodsMinus) {
                val num: Int = itemData.cart_num - 1
                if (num == 0) {
                    viewModel.cartRemove(itemData.goods_id, itemData.cart_id)
                } else {
                    viewModel.cartChangeNum1(itemData.goods_id, itemData.cart_id, num)
                }
            }
        }

        mSmartRefreshLayout.setEnableRefresh(false)
        mSmartRefreshLayout.setEnableLoadMore(false)
        mSmartRefreshLayout.setOnLoadMoreListener {
            viewModel.userCollectList(isLoadMore = true)
        }
    }

    override fun initData() {
        viewModel.userCollectList()
    }

    override fun initViewMode() {


        viewModel.collectGoodsLiveDate.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg ?: "位置错误")
                mSmartRefreshLayout.finishLoadMore((false))
            } else if (response.status == Status.SUCCESS) {
                mSmartRefreshLayout.finishLoadMore()
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.data?.let {
                if (it.data.size == 0) {
                    mCollectGoodsAdapter.setEmptyView(createEmptyView())
                }
                if (it.loadMore) {
                    mCollectGoodsAdapter.addData(it.data)
                } else {
                    mCollectGoodsAdapter.setNewInstance(it.data)
                }
                if (it.data.size < viewModel.rows) {
                    mCollectGoodsAdapter.setFooterView(createFooterView())
                    mSmartRefreshLayout.setEnableLoadMore(false)
                } else {
                    mCollectGoodsAdapter.removeAllFooterView()
                    mSmartRefreshLayout.setEnableLoadMore(true)
                }
            }
        })

        //监听购物车添加
        viewModel.cartAdd1LiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车加减
        viewModel.cartChangeNum1LiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        //监听购物车删除
        viewModel.cartDelete1LiveData.observe(this as LifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.status.desc)
            }
        })
    }

    override fun onEventMainThread(any: Any) {
        if (any !is CartAction)
            return
        if (any.action == CartAction.Action.CLEAR) {
            val position = mutableListOf<Int>()
            for ((index, item) in mCollectGoodsAdapter.data.withIndex()) {
                if (item.cart_num != 0) position.add(index)
            }
            position.forEach {
                mCollectGoodsAdapter.setData(it)
            }
        } else {
            val position = mCollectGoodsAdapter.data.indexOfFirst {
                it.goods_id == any.goodsId
            }
            if (position == -1)
                return
            mCollectGoodsAdapter.setData(position, any.goodsNum, any.cartId)
        }
    }

    private fun createEmptyView(): View {
        return layoutInflater.inflate(R.layout.view_empty_error, null)
    }

    private fun createFooterView(): View = TextView(this).apply {
        layoutParams = FrameLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            ConvertUtils.dp2px(30f)
        )
        gravity = Gravity.CENTER
        textSize = 13f
        text = "没有更多商品"
        setTypeface(null, Typeface.BOLD)
        setTextColor(ColorUtils.getColor(R.color.FF_666666))
    }
}